package com.atguigu.spzx.pay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.atguigu.spzx.feign.order.OrderFeignClient;
import com.atguigu.spzx.feign.product.ProductFeignClient;
import com.atguigu.spzx.model.entity.order.OrderInfo;
import com.atguigu.spzx.model.entity.order.OrderItem;
import com.atguigu.spzx.pay.service.PayService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PayServiceImpl implements PayService {

    @Autowired
    OrderFeignClient orderFeignClient;

    @Autowired
    ProductFeignClient productFeignClient;

    @SneakyThrows
    @Override
    public String submitAlipay(String orderNo) {
        String publicKey="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhR/iM913rnVnGUGlg1iDqgpJ7K3d4hgYjiV0Cupu/43VYSxzR6KMEmrg/M+xOhg18p0QjO7f24BQIuFFSaz5jxyWWy3n74yES8FtzJXnHNFt+AZypE2JaCcqRNUTE19tmavzlb1B7AZtjw4plhprPHuvNg0MATZj9TyqmNKk9OuOykSl+Sqf45mncZFUDuVtRegN220lbVJS/vpDkKqla9Dzpm26FuyjMSnjfhgL9zPFjgHqRqPJapNDswlZA/XR+iEd/59hz56GS6jk0jFsxZ8aayydSOltRDhrgd52ucywG5ZtgrFhtfhnxTAA2mDLkKHJ6XM5fuws3uTHCvPTSwIDAQAB";
        String privateKey="MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCFH+Iz3XeudWcZQaWDWIOqCknsrd3iGBiOJXQK6m7/jdVhLHNHoowSauD8z7E6GDXynRCM7t/bgFAi4UVJrPmPHJZbLefvjIRLwW3Mlecc0W34BnKkTYloJypE1RMTX22Zq/OVvUHsBm2PDimWGms8e682DQwBNmP1PKqY0qT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diADVufzWou9sKB6X5d4HaBN/1w10vCTcMzRAp6VGvj7tVgjyg5oDTDzkDK2ACoqKt2JSsJ1Zocpm8vto3kiOnqlsYtPXpq4zdZzw7qPKebjftia21/u4Ywazi852Txb8CHHK8stBpyiIvrygcHf5RNpoPV0CgYEAwAV1LrcS7RWIl8uOM/0ZMuEUfj9k6KFhbYi3Gydr5eAHzWIbMnzGod+lgoo2kPXyR00SuJfIeXCGHhyNXKQK43Kf45WUrWH8ZTlObqeqlbYoqld0flK4ieDPBDnDtqSoaSZXp2DJ9tS33wHrVFAtb2W9OfiNpfTiasWjDzziDEw=";
        String appId="9021000143665441";

        // 初始化SDK  阿里支付客户端
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi-sandbox.dl.alipaydev.com/gateway.do",
                appId,privateKey,"json","utf-8",publicKey,"RSA2");
        // 构造请求参数以调用接口
        AlipayTradeWapPayRequest alipayTradeWapPayRequest = new AlipayTradeWapPayRequest();

        //设置参数前,需要根据orderNo订单号去查询到该订单详情,然后填写支付参数
        OrderInfo orderInfo= orderFeignClient.getOrderInfoByOrderNo(orderNo);
        //设置参数
        //设置支付信息参数
        Map<String,Object> map =new HashMap<>();
        map.put("out_trade_no",orderNo);  //我们网站生成的唯一订单号
        map.put("total_amount",orderInfo.getTotalAmount());    //总支付金额
        map.put("subject",orderInfo.getOrderItemList().get(0).getSkuName());  //支付订单的主题
        map.put("product_code",orderInfo.getId());  //商品编号
        alipayTradeWapPayRequest.setBizContent(JSON.toJSONString(map));
        //设置支付后跳转以及异步url
        alipayTradeWapPayRequest.setReturnUrl("http://192.168.83.123/#/pages/money/paySuccess");
        //回调地址,需要在公网上,支付宝回调该接口.  我们可以使用内网穿透技术,natapp  .
        alipayTradeWapPayRequest.setNotifyUrl(" http://ieqtvh.natappfree.cc/api/order/alipay/callback/notify");


        //调用支付
        String payForm = alipayClient.pageExecute(alipayTradeWapPayRequest).getBody();
        System.out.println(payForm);

        return payForm;

    }

    @Transactional
    @Override
    public void handlePaymentCallback(Map<String, String> paramMap) {
        //获取到订单号
        String orderNo = paramMap.get("out_trade_no");
        //根据订单号查找到订单项
        OrderInfo orderInfo= orderFeignClient.getOrderInfoByOrderNo(orderNo);
        List<OrderItem> orderItemList = orderInfo.getOrderItemList();
        //根据订单项去修改库存
        for (OrderItem orderItem : orderItemList) {

            //获取到商品id以及数量进行商品库存更新
            Long skuId = orderItem.getSkuId();
            Integer skuNum = orderItem.getSkuNum();
            Boolean updateStockFlag= productFeignClient.updateStock(skuId,skuNum);
            //如果更新失败，直接抛出异常
            if(!updateStockFlag){
                //库存不足更新失败，出发退款并抛出异常
                throw new RuntimeException("库存不足，下单失败");
            }
        }
    }
}
